% 
% @author glogo4j
%

% Erlang try-catch demo


-module(try_test).

-export ([demo1/0, demo2/0, improved_error_report_test/1, demo3/0]).

% 抛出所有类型的异常
generate_exception(1) -> a;
generate_exception(2) -> throw(a);
generate_exception(3) -> exit(a);
generate_exception(4) -> {'EXIT', a};
generate_exception(5) -> erlang:error(a).

demo1() -> [ cather(I) || I <- [1,2,3,4,5]].

demo2() -> [{I, cather(I)} || I <- [1,2,3,4,5]].

demo3() -> 
	try generate_exception(5)
	catch 
		error : X -> {X, erlang:get_stacktrace()}
	end.

cather(N) -> 
	try generate_exception(N) of
		Val -> {N, normal, Val}
	catch
		throw : X -> {N, caught, thrown, X};
		exit: X -> {N, caught, exitd, X};
		error: X -> {N, caught, error, X}
	end.


sqrt(N) when N < 0 ->
	erlang:error({squareRootNegativeArgument,N});
sqrt(N) -> 
	math:sqrt(N).

improved_error_report_test(N) -> sqrt(N).